package com.example.newwork

import android.util.Log
import android.view.View
import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch


class NetViewModel:ViewModel() {

    val listData = MutableLiveData<NetResource<List<ArticleBean>>> ().apply{
        NetResource.doLoading(true)
    }
    private val serviceFlow by lazy {
        getFlowService(MainApi::class.java)
    }
    private val serviceLiveData by lazy {
        getLiveDataService(MainApi::class.java)
    }

    private val service by lazy {
        getService(MainApi::class.java)
    }


    fun startIntentEvents(netWorkEvent: NetWorkEvent){
        when(netWorkEvent){
            NetWorkEvent.RemoteDataByCommon -> getArticleData()
            NetWorkEvent.RemoteDataByFlow -> getFlowArticleData()
            NetWorkEvent.RemoteDataByLiveData ->getLiveDataArticle()
        }
    }


    fun getFlowArticleData(){
        serviceFlow.getFlowArticles()
                .flowOn(Dispatchers.IO)
                .onEach{
                Log.i("TAG141", "Flow:${it.errorCode} ${Thread.currentThread().name}")
            }.launchIn(viewModelScope)

    }
    fun getArticleData(){
        viewModelScope.launch(Dispatchers.IO){
               val data  = async {
                   service.getCommonArticles()
               }.await()

            Log.i("TAG141", "Flow:${data.errorCode} ${Thread.currentThread().name}")


        }
    }
    private fun getLiveDataArticle(){
        viewModelScope.launch(Dispatchers.IO) {
            listData.postValue(NetResource.doLoading(true))
             val  data =  async {
                   serviceLiveData.getCommonArticles()
               }.await()
            if (data?.errorCode==0){
                listData.postValue(NetResource.doSuccess(data?.data?.datas))
            }else{
                listData.postValue(NetResource.doFailure("出错拉！"))
            }


        }
    }

}